<?php

namespace api\modules\v1\models;

use api\common\models\Mar;
use Yii;
use api\common\models\Common;
use yii\db\Query;

class Visitor extends Common
{

    /**
     * @return array|string
     */
    public static function tableName()
    {
        return '{{%visitor_app}}';
    }


    public function rules()
    {
        return [
        ];
    }

    /*
     * 添加浏览历史记录
     * @param $uid
     * @param $catid
     * @param $news_id
     * @return bool
     */
    public function add($uid,$visitor_uid){
        //uid 被访问者的id
        //visitor_uid 访问者id
        if($uid !='' && $visitor_uid !=''){
            if($data = self::findOne(['uid'=>$visitor_uid,'visitor_uid'=>$uid])){
                self::updateAll(['time'=>date('Y-m-d H:i:s')],['id'=>$data->id]);
            }else{
                $count = (new Query())
                    ->from(self::tableName().' as a')
                    ->innerJoin('{{%user_app}} as b','a.visitor_uid = b.`id`')
                    ->where("a.uid = ".$visitor_uid)
                    ->count();
                //$count = count(self::findAll(['uid'=>$visitor_uid]));
                if($count >= 20){ //最多只能存20条记录
                    $first_id = (new Query())
                        ->select('a.id')
                        ->from(self::tableName().' as a')
                        ->innerJoin('{{%user_app}} as b','a.visitor_uid = b.`id`')
                        ->where("a.uid = ".$visitor_uid)
                        ->orderBy('time asc')
                        ->limit(1)
                        ->one();
                    //$first_id = self::find()->where(['uid'=>$visitor_uid])->orderBy('id asc')->limit(1)->one();//删除最开始的一条
                    self::deleteAll(['id'=>$first_id['id']]);
                }
                $this->uid = $visitor_uid;
                $this->visitor_uid = $uid;
                $this->time = date('Y-m-d H:i:s');
                $this->isNewRecord = true;
                $this->save(false);
            }
        }
        return true;
    }

    /*
     * 访问历史记录
     * @param $uid
     * @param $visitor_uid
     * @return bool
     */
    public function history($uid,$visitor_uid){
        //uid 被访问者的id
        //visitor_uid 访问者id
        if($uid !='' && $visitor_uid !=''){
            $_table = '{{%visitor_history_app}}';
            $visitor_history = new Mar($_table);
            if(!$data = $visitor_history->findOnex($_table,['uid'=>$visitor_uid,'visitor_uid'=>$uid,'time'=>date('Y-m-d')])) {
                $visitor_history->uid = $visitor_uid;
                $visitor_history->visitor_uid = $uid;
                $visitor_history->time = date('Y-m-d');
                $visitor_history->isNewRecord = true;
                $visitor_history->save(false);
            }
        }
        return true;
    }
}
